#include "datablock_manager.h"
#include "ui_datablock_manager.h"

datablock_manager::datablock_manager(QWidget *parent)
    : QWidget(parent), ui(new Ui::datablock_manager)
{
    ui->setupUi(this);
    initUi();
    // this->setStyleSheet("");
    setAttribute(Qt::WA_StyledBackground); // 这句不加,样式表是加载不出来的

    // 为四个frame设置特定的objectName，避免被全局样式覆盖
    ui->frame_temp->setObjectName("frame_temp");
    ui->frame_hum->setObjectName("frame_hum");
    ui->frame_ultrasonic->setObjectName("frame_ultrasonic");
    ui->frame_tev->setObjectName("frame_tev");

    // 初始化四个块的样式为离线状态
    updateFrameStyle(ui->frame_temp, "离线");
    updateFrameStyle(ui->frame_hum, "离线");
    updateFrameStyle(ui->frame_ultrasonic, "离线");
    updateFrameStyle(ui->frame_tev, "离线");
}

datablock_manager::~datablock_manager()
{
    QMutexLocker locker(&m_mutex);
    qDeleteAll(m_handleMap); // 删除所有该map下的实例
    m_handleMap.clear();
    m_dataIdMap.clear();
    delete ui;
}
/**
 * @brief datablock_manager::init_ui 初始化布局为格子,并设置为6列
 */
void datablock_manager::initUi()
{
    ui->widget_label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
    ui->widget_positioninfo->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    // 删除现有布局
    if (ui->widget_positioninfo->layout())
    {
        delete ui->widget_positioninfo->layout();
    }

    m_gridLayout = new QGridLayout(ui->widget_positioninfo);
    m_gridLayout->setContentsMargins(10, 0, 0, 0);
    m_gridLayout->setSpacing(5);
    for (int i = 0; i < m_itemsPerRow; ++i)
    {
        m_gridLayout->setColumnStretch(i, 1);
    }
    // 强行让父界面布局计算
    if (QWidget *parent = ui->widget_positioninfo->parentWidget())
    {
        if (QLayout *parentLayout = parent->layout())
        {
            parentLayout->activate();
            QApplication::processEvents(); // 处理布局事件
        }
    }
    // qDebug() << "size init: "<< size();
    // qDebug() << "widget_positioninfo size init: "<< ui->widget_positioninfo->size();
    // qDebug() << "widget_label size init: "<< ui->widget_label->size();
}
/**
 * @brief datablock_manager::createBlock 创建一个新的block,返回这个block的句柄,后续删除依赖这个句柄
 * @param data 传入block需要的信息
 * @return
 */
int datablock_manager::createBlock(const DataBlock &data)
{
    QMutexLocker locker(&m_mutex);
    // 检查数据ID是否已存在
    if (m_dataIdMap.contains(data.id))
    {
        // qWarning() << "Data ID" << data.id << "already exists";
        return -1;
    }

    // 生成唯一句柄ID
    const int handleId = data.identifier.toInt(); // generateHandleId();

    // 创建控件实例,由manager页面下的位置信息页面管理
    auto *info = new datablock_info(ui->widget_positioninfo);
    // 设置参数失败删除类
    if (!info->setBlockInfo(data))
    {
        delete info;
        return -1;
    }

    // 建立双向映射
    m_handleMap.insert(handleId, QPointer<datablock_info>(info)); // 显式构造 QPointer
    m_dataIdMap.insert(data.id, handleId);
    m_insertionOrder.append(handleId); // 记录插入顺序

    // 打印插入顺序信息
    qDebug() << "创建参数块 - 标识符:" << data.identifier
             << "ID:" << data.id
             << "位置:" << data.position
             << "类型:" << data.type
             << "当前插入顺序索引:" << m_insertionOrder.size() - 1;

    emit blockCreated(handleId);
    return handleId;
}

/**
 * @brief datablock_manager::deleteBlock 根据传入的句柄,删除对应数据块
 * @param handleId
 * @return
 */
bool datablock_manager::deleteBlock(int handleId)
{
    QMutexLocker locker(&m_mutex);
    // 正确获取 QPointer 对象
    QPointer<datablock_info> info = m_handleMap.take(handleId);
    if (!info.isNull())
    { // 检查指针有效性
        m_dataIdMap.remove(info->id());
        m_insertionOrder.removeOne(handleId); // 从插入顺序列表中移除

        // 打印删除信息
        qDebug() << "删除参数块 - 句柄ID:" << handleId
                 << "ID:" << info->id();

        emit blockRemoved(handleId);
        delete info.data(); // 安全删除原始指针
        return true;
    }
    return false;
}

/**
 * @brief updateBlockData 更新数据块信息
 * @param handleId
 * @param newData
 * @return
 */
bool datablock_manager::updateBlockData(int handleId, const DataBlock &newData)
{
    QMutexLocker locker(&m_mutex);
    if (!m_handleMap.contains(handleId))
        return false;

    QPointer<datablock_info> info = m_handleMap[handleId];
    if (info.isNull())
        return false;

    const int oldId = info->id();
    if (!info->setBlockInfo(newData))
        return false;

    if (newData.id != oldId)
    {
        if (m_dataIdMap.contains(newData.id))
            return false;
        m_dataIdMap.remove(oldId);
        m_dataIdMap.insert(newData.id, handleId);
    }
    return true;
}

/**
 * @brief setItemsPerRow 设置一行最多显示的数据块数量
 * @param maxRow
 */
void datablock_manager::setItemsPerRow(int maxRow)
{
    m_itemsPerRow = maxRow;
}

void datablock_manager::setBlockName(QString name)
{
    ui->label_name->setText(name);
}

void datablock_manager::setTemperatureThreshold(double threshold)
{
    QMutexLocker locker(&m_mutex);
    m_temperatureThreshold = threshold;
    // 为所有温度类型的 datablock_info 设置阈值
    for (auto &block : m_handleMap)
    {
        if (!block.isNull())
        {
            // 判断是否为温度类型（需要根据实际数据结构判断）
            // 这里假设可以通过 icon_path 判断类型
            const DataBlock &data = block->blockData();
            if (data.icon_path.contains("t_blue"))
            { // 温度图标
                block->setCriticalThreshold(threshold);
            }
        }
    }
}

void datablock_manager::setHumidityThreshold(double threshold)
{
    QMutexLocker locker(&m_mutex);
    m_humidityThreshold = threshold;
    // 为所有湿度类型的 datablock_info 设置阈值
    for (auto &block : m_handleMap)
    {
        if (!block.isNull())
        {
            // 判断是否为湿度类型
            const DataBlock &data = block->blockData();
            if (data.icon_path.contains("h_blue"))
            { // 湿度图标
                block->setCriticalThreshold(threshold);
            }
        }
    }
}
/**
 * @brief datablock_manager::updateLayout 更新布局,宽高会根据子控件进行变化
 */
void datablock_manager::updateLayout()
{
    // 移除所有布局项，但不删除控件
    while (QLayoutItem *item = m_gridLayout->takeAt(0))
    {
        delete item;
    }

    // 重置所有子控件的尺寸约束
    for (auto it = m_handleMap.begin(); it != m_handleMap.end(); ++it)
    {
        if (!it.value().isNull())
        {
            it.value()->setMinimumSize(0, 0);                             // 重置最小尺寸
            it.value()->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); // 重置最大尺寸
        }
    }

    // 设置每列的拉伸系数为1，确保等宽
    for (int col = 0; col < m_itemsPerRow; ++col)
    {
        m_gridLayout->setColumnStretch(col, 1);
    }
    int parentWidth = ui->widget_positioninfo->width();

    int row = 0, col = 0;
    int hSpacing = m_gridLayout->horizontalSpacing();
    int availableWidth = parentWidth - hSpacing * (m_itemsPerRow - 1);
    int itemWidth = qMax(availableWidth / m_itemsPerRow, 1);
    int itemHeight = itemWidth * 0.6;

    // 打印布局开始信息
    qDebug() << "开始布局参数块 - 总数量:" << m_insertionOrder.size()
             << "每行数量:" << m_itemsPerRow
             << "父容器宽度:" << parentWidth
             << "项目宽度:" << itemWidth
             << "项目高度:" << itemHeight;

    // 按插入顺序添加控件到布局
    for (int i = 0; i < m_insertionOrder.size(); ++i)
    {
        int handleId = m_insertionOrder[i];
        QPointer<datablock_info> block = m_handleMap.value(handleId);
        if (block.isNull())
            continue;

        block->setMinimumSize(itemWidth, itemHeight);

        // 打印每个块的布局信息
        qDebug() << "布局参数块 - 索引:" << i
                 << "句柄ID:" << handleId
                 << "位置:" << block->blockData().position
                 << "类型:" << block->blockData().type
                 << "网格位置: 行" << row << "列" << col;

        m_gridLayout->addWidget(block, row, col);

        if (++col >= m_itemsPerRow)
        {
            col = 0;
            row++;
        }
    }

    // 准确计算总行数
    int vSpacing = m_gridLayout->verticalSpacing();
    int totalRows = (m_insertionOrder.size() + m_itemsPerRow - 1) / m_itemsPerRow;
    // int totalHeight = totalRows * itemHeight + (totalRows+1) * vSpacing;
    // 修改总高度计算公式
    int totalHeight = totalRows * itemHeight + (totalRows - 1) * vSpacing;
    // 设置容器高度并强制刷新布局
    ui->widget_positioninfo->setFixedHeight(totalHeight);
    setFixedHeight(totalHeight + ui->widget_label->height() + 10);
    // 关键：强制主窗口重新计算布局
    this->adjustSize();
    this->parentWidget()->adjustSize(); // 如果主窗口有父容器，可能需要更新父布局

    // 打印布局完成信息
    qDebug() << "布局完成 - 总行数:" << totalRows
             << "总高度:" << totalHeight
             << "容器总高度:" << this->height();
}

void datablock_manager::on_pushButton_info_clicked()
{
    QString block_name = ui->label_name->text();
    emit signalToForward("information :" + block_name);
}

void datablock_manager::on_pushButton_info_released()
{
}

void datablock_manager::setTempInVisible(bool visible)
{
    ui->frame_temp->setVisible(visible);
}
void datablock_manager::setHumInVisible(bool visible)
{
    ui->frame_hum->setVisible(visible);
}

/**
 * @brief updateFrameStyle 根据状态更新frame的样式
 * @param frame 要更新的frame
 * @param status 状态字符串："离线"、"在线"、"警告"
 */
void datablock_manager::updateFrameStyle(QFrame *frame, const QString &status)
{
    if (!frame)
        return;

    QString styleSheet;
    QString frameName = frame->objectName();

    if (status == "离线")
    {
        // 离线状态：灰色边框，深灰色背景
        styleSheet = QString(
                         "#%1 {"
                         "    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                         "                                      stop:0 #3E3E3E, stop:1 #2D2D2D);"
                         "    border: 2px solid #808080;"
                         "    border-radius: 8px;"
                         "    padding: 4px;"
                         "}"
                         "#%1 * {"
                         "    background-color: transparent;"
                         "    border-color: transparent;"
                         "}")
                         .arg(frameName);
    }
    else if (status == "警告")
    {
        // 报警状态：红色边框，红色渐变背景
        styleSheet = QString(
                         "#%1 {"
                         "    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                         "                                      stop:0 #FF3B30, stop:1 #D63031);"
                         "    border: 2px solid #FF0000;"
                         "    border-radius: 8px;"
                         "    padding: 4px;"
                         "}"
                         "#%1 * {"
                         "    background-color: transparent;"
                         "    border-color: transparent;"
                         "}")
                         .arg(frameName);
    }
    else
    {
        // 在线状态：蓝色边框，默认渐变背景
        styleSheet = QString(
                         "#%1 {"
                         "    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                         "                                      stop:0 #1C3F7D, stop:1 #0F2D5E);"
                         "    border: 2px solid #00A3FF;"
                         "    border-radius: 8px;"
                         "    padding: 4px;"
                         "}"
                         "#%1 * {"
                         "    background-color: transparent;"
                         "    border-color: transparent;"
                         "}")
                         .arg(frameName);
    }

    frame->setStyleSheet(styleSheet);
}

void datablock_manager::setTempIn(QString temp)
{
    QString status;
    if (temp == "--")
    {
        status = "离线";
        ui->label_temp->setText(temp);
        ui->label_Tstatus->setText(status);
    }
    else
    {
        double num = temp.toDouble();
        ui->label_temp->setText(QString::number(num, 'f', 1));
        if (num < m_temperatureThreshold)
        {
            status = "在线";

            ui->label_Tstatus->setText(status);
        }
        else
        {
            status = "警告";
            ui->label_Tstatus->setText(status);
        }
    }
    // 更新温度frame的样式
    updateFrameStyle(ui->frame_temp, status);
}

void datablock_manager::setHumIn(QString hum)
{

    QString status;
    if (hum == "--")
    {
        status = "离线";
        ui->label_hum->setText(hum);
        ui->label_Hstatus->setText(status);
    }
    else
    {
        double num = hum.toDouble();
        ui->label_hum->setText(QString::number(num, 'f', 1));
        if (num < m_humidityThreshold)
        {
            status = "在线";
            ui->label_Hstatus->setText(status);
        }
        else
        {
            status = "警告";
            ui->label_Hstatus->setText(status);
        }
    }
    // 更新湿度frame的样式
    updateFrameStyle(ui->frame_hum, status);
}
void datablock_manager::setUltrasonicThreshold(double threshold)
{
    QMutexLocker locker(&m_mutex);
    m_ultrasonicThreshold = threshold;
    // 为所有超声波类型的 datablock_info 设置阈值
    for (auto &block : m_handleMap)
    {
        if (!block.isNull())
        {
            // 判断是否为超声波类型
            const DataBlock &data = block->blockData();
            if (data.icon_path.contains("icon_shark") && data.unit == "dBuV")
            { // 超声波图标和单位
                block->setCriticalThreshold(threshold);
            }
        }
    }
}

void datablock_manager::setTEVThreshold(double threshold)
{
    QMutexLocker locker(&m_mutex);
    m_tevThreshold = threshold;
    // 为所有暂态地电压类型的 datablock_info 设置阈值
    for (auto &block : m_handleMap)
    {
        if (!block.isNull())
        {
            // 判断是否为暂态地电压类型
            const DataBlock &data = block->blockData();
            if (data.icon_path.contains("icon_light") && data.unit == "dBmV")
            { // 暂态地电压图标和单位
                block->setCriticalThreshold(threshold);
            }
        }
    }
}

void datablock_manager::setUltrasonicVisible(bool visible)
{
    if (ui->frame_ultrasonic)
    {
        ui->frame_ultrasonic->setVisible(visible);
    }
}

void datablock_manager::setTEVVisible(bool visible)
{
    if (ui->frame_tev)
    {
        ui->frame_tev->setVisible(visible);
    }
}

void datablock_manager::setUltrasonicData(QString data)
{
    // if (ui->label_ultrasonic)
    // {
    //     bool ok;
    //     double num = data.toDouble(&ok);
    //     if (ok)
    //     {
    //         // 成功转换为数字，格式化为一位小数
    //         ui->label_ultrasonic->setText(QString::number(num, 'f', 1));
    //     }
    //     else
    //     {
    //         // 非数字情况（如"--"）直接显示
    //         ui->label_ultrasonic->setText(data);
    //     }
    //     // ui->label_ultrasonic->setText(data);
    // }

    QString status;
    if (ui->label_Ustatus)
    {
        if (data == "--")
        {
            status = "离线";
            ui->label_ultrasonic->setText(data);
            ui->label_Ustatus->setText(status);
        }
        else
        {
            double num = data.toDouble();
            ui->label_ultrasonic->setText(QString::number(num, 'f', 1));
            if (num < m_ultrasonicThreshold)
            {
                status = "在线";
                ui->label_Ustatus->setText(status);
            }
            else
            {
                status = "警告";
                ui->label_Ustatus->setText(status);
            }
        }
    }
    // 更新超声波frame的样式
    updateFrameStyle(ui->frame_ultrasonic, status);
}

void datablock_manager::setTEVData(QString data)
{
    // if (ui->label_tev)
    // {
    //     bool ok;
    //     double num = data.toDouble(&ok);
    //     if (ok)
    //     {
    //         // 成功转换为数字，格式化为一位小数
    //         ui->label_tev->setText(QString::number(num, 'f', 1));
    //     }
    //     else
    //     {
    //         // 非数字情况（如"--"）直接显示
    //         ui->label_tev->setText(data);
    //     }
    //     // ui->label_tev->setText(data);
    // }

    QString status;
    if (ui->label_TEVstatus)
    {
        if (data == "--")
        {
            status = "离线";
            ui->label_tev->setText(data);
            ui->label_TEVstatus->setText(status);
        }
        else
        {
            double num = data.toDouble();
            ui->label_tev->setText(QString::number(num, 'f', 1));
            if (num < m_tevThreshold)
            {
                status = "在线";
                ui->label_TEVstatus->setText(status);
            }
            else
            {
                status = "警告";
                ui->label_TEVstatus->setText(status);
            }
        }
    }
    // 更新暂态地电压frame的样式
    updateFrameStyle(ui->frame_tev, status);
}